<!-- ❗Errors in the form are set on line 60 -->
<template>
  <RouterLink to="/">
    <div class="auth-logo d-flex align-center gap-x-3">
      <VNodeRenderer :nodes="themeConfig.app.logo" />
      <h1 class="auth-title">
        {{ themeConfig.app.title }}
      </h1>
    </div>
  </RouterLink>

  <VRow no-gutters class="auth-wrapper bg-surface">
    <VCol md="8" class="d-none d-md-flex">
      <div class="position-relative bg-background w-100 me-0">
        <div class="d-flex align-center justify-center w-100 h-100" style="padding-inline: 6.25rem;">
          <VImg max-width="613" :src="authThemeImg" class="auth-illustration mt-16 mb-2" />
        </div>

        <img class="auth-footer-mask" :src="authThemeMask" alt="auth-footer-mask" height="280" width="100">
      </div>
    </VCol>

    <VCol cols="12" md="4" class="auth-card-v2 d-flex align-center justify-center">
      <VCard flat :max-width="500" class="mt-12 mt-sm-0 pa-4">
        <VCardText>
          <h4 class="text-h4 mb-1">
            Welcome to <span class="text-capitalize"> {{ themeConfig.app.title }} </span>! 👋🏻
          </h4>
          <p class="mb-0">
            Please sign-in to your account and start the adventure
          </p>
        </VCardText>
        <VCardText>
          <VForm ref="refVForm" @submit.prevent="onSubmit">
            <VRow>
              <!-- 租户id -->
              <VCol cols="12">
                <AppTextField v-model="credentials.tenantId" :label="$t('login.tenant')" :placeholder="$t('login.tenant')" type="text" :rules="[requiredValidator]" />
              </VCol>
              <!-- email -->
              <VCol cols="12">
                <AppTextField v-model="credentials.username" :label="$t('login.username')" :placeholder="$t('login.username')" type="text" :rules="[requiredValidator]" :error-messages="errors.username" />
              </VCol>
              <!-- password -->
              <VCol cols="12">
                <AppTextField v-model="credentials.password" :label="$t('login.password')" placeholder="············" :rules="[requiredValidator]" :type="isPasswordVisible ? 'text' : 'password'" :error-messages="errors.password" :append-inner-icon="isPasswordVisible ? 'tabler-eye-off' : 'tabler-eye'" @click:append-inner="isPasswordVisible = !isPasswordVisible" />
                <div class="d-flex align-center flex-wrap justify-space-between my-6">
                  <VCheckbox v-model="rememberMe" :label="$t('login.rememberMe')" />
                  <I18n  v-if="themeConfig.app.i18n.enable && themeConfig.app.i18n.langConfig?.length"
                  :languages="themeConfig.app.i18n.langConfig"/>
                  <!-- <RouterLink
                    class="text-primary ms-2 mb-1"
                    :to="{ name: 'forgot-password' }"
                  >
                    Forgot Password?
                  </RouterLink> -->
                </div>
                <VBtn block type="submit" v-loading="loading">
                  {{$t('login.loginBtn')}}
                </VBtn>
              </VCol>
            </VRow>
          </VForm>
        </VCardText>
      </VCard>
    </VCol>
  </VRow>
</template>

<script setup>
import { VForm } from "vuetify/components/VForm";
import AuthProvider from "@/views/pages/authentication/AuthProvider.vue";
import { useGenerateImageVariant } from "@core/composable/useGenerateImageVariant";
import authV2LoginIllustrationBorderedDark from "@images/pages/auth-v2-login-illustration-bordered-dark.png";
import authV2LoginIllustrationBorderedLight from "@images/pages/auth-v2-login-illustration-bordered-light.png";
import authV2LoginIllustrationDark from "@images/pages/auth-v2-login-illustration-dark.png";
import authV2LoginIllustrationLight from "@images/pages/auth-v2-login-illustration-light.png";
import authV2MaskDark from "@images/pages/misc-mask-dark.png";
import authV2MaskLight from "@images/pages/misc-mask-light.png";
import { VNodeRenderer } from "@layouts/components/VNodeRenderer";
import { themeConfig } from "@themeConfig";
import { toast } from "vuetify-sonner";
import I18n from "@core/components/I18n.vue";
import { useStorage } from "@vueuse/core";
const authThemeImg = useGenerateImageVariant(
  authV2LoginIllustrationLight,
  authV2LoginIllustrationDark,
  authV2LoginIllustrationBorderedLight,
  authV2LoginIllustrationBorderedDark,
  true
);
const authThemeMask = useGenerateImageVariant(authV2MaskLight, authV2MaskDark);

definePage({
  meta: {
    layout: "blank",
    unauthenticatedOnly: true,
  },
});

const loading = ref(false);

const isPasswordVisible = ref(false);
const route = useRoute();
const router = useRouter();
const ability = useAbility();

const errors = ref({
  username: undefined,
  password: undefined,
});

const refVForm = ref();

const username = localStorage.getItem("username") || "";
const password = "";
const tenantId = localStorage.getItem("tenantId") || "";
const credentials = ref({
  username,
  password,
  tenantId,
});
const localAccessToken = useStorage("accessToken", "",localStorage);
const sessionAccessToken = useStorage("accessToken", "",sessionStorage);
const rememberMe = ref(true);
const rememberMeAction = function (accessToken) {
  localAccessToken.value = accessToken;
  localStorage.setItem("username", credentials.value.username || username);
  localStorage.setItem("tenantId", credentials.value.tenantId || tenantId);
};
const login = async () => {
  loading.value = true;
  const res = await $api("/auth/login", {
    method: "POST",
    body: {
      grantType: "password",
      tenantId: credentials.value.tenantId,
      username: credentials.value.username,
      password: credentials.value.password,
      clientId: "e5cd7e4891bf95d1d19206ce24a7b32e",
    }
  }).finally(() => {
    loading.value = false;
  });

  if (rememberMe.value) {
    rememberMeAction(res.data.access_token);
  }else{
    sessionAccessToken.value = res.data.access_token;
  }
  
  await nextTick(() => {
    router.replace(route.query.to ? String(route.query.to) : "/");
  });
};

const onSubmit = () => {
  refVForm.value?.validate().then(({ valid: isValid }) => {
    if (isValid) login();
  });
};
</script>

<style lang="scss">
@use "@core/scss/template/pages/page-auth.scss";
</style>
